package com.zzyl.common.utils;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.AbstractCredentials;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.region.Region;
import com.huaweicloud.sdk.iotda.v5.*;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.config.HuaWeiIotConfigProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description HuaweiUtil
 * @Author cangyue
 * @Date 2025-07-20
 */
@Component
public class HuaweiUtil {
    @Resource
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    //获取IoTDAClient
    public IoTDAClient getIoTDAClient() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        String ak = huaWeiIotConfigProperties.getAk();
        String sk = huaWeiIotConfigProperties.getSk();
        // ENDPOINT：请在控制台的"总览"界面的"平台接入地址"中查看“应用侧”的https接入地址。
        String iotdaEndpoint = huaWeiIotConfigProperties.getEndpoint();

        ICredential auth = new BasicCredentials()
                // 标准版/企业版需要使用衍生算法，基础版请删除配置"withDerivedPredicate";
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                .withAk(ak)
                .withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth)
                // 标准版/企业版：需自行创建Region对象，基础版：请使用IoTDARegion的region对象，如"withRegion(IoTDARegion.CN_NORTH_4)"
                .withRegion(new Region(huaWeiIotConfigProperties.getRegionId(), iotdaEndpoint))
                .build();
        return client;
    }
    // 获取产品列表
    public List<ProductSummary> get() {
        ListProductsRequest request = new ListProductsRequest();
        try {
            ListProductsResponse response = getIoTDAClient().listProducts(request);
            List<ProductSummary> products = response.getProducts();
            return products;
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return null;
    }
    // 添加设备

    public AddDeviceResponse add(String projectId, String nodeId, String name,String  description) {
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(projectId);
        body.withDeviceName(name);
        body.withNodeId(nodeId);
        if (description != null){
            body.withDescription(description);
        }
        request.withBody(body);
        try {
            AddDeviceResponse response = getIoTDAClient().addDevice(request);
            return response;
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return null;
    }

    // 获取设备详情
    public ShowDeviceResponse getDevice(String deviceId, String projectId){
        ICredential auth = new BasicCredentials()
                .withProjectId(projectId)
                // 标准版/企业版需要使用衍生算法，基础版请删除配置"withDerivedPredicate";
                .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                .withAk(huaWeiIotConfigProperties.getAk())
                .withSk(huaWeiIotConfigProperties.getSk());

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth)
                // 标准版/企业版：需自行创建Region对象，基础版：请使用IoTDARegion的region对象，如"withRegion(IoTDARegion.CN_NORTH_4)"
                .withRegion(new Region(huaWeiIotConfigProperties.getRegionId(), huaWeiIotConfigProperties.getEndpoint()))
                .build();
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(deviceId);
        try {
            ShowDeviceResponse response = client.showDevice(request);
            return response;
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return null;
    }

    public UpdateDeviceResponse UpdateDeviceSolution(String deviceId, String deviceName) {

            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.withDeviceId(deviceId);
            UpdateDevice body = new UpdateDevice();
            body.withDeviceName(deviceName);
            request.withBody(body);
            try {
                UpdateDeviceResponse response = getIoTDAClient().updateDevice(request);
                return response;
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
            return null;
        }

        // 删除设备
    public DeleteDeviceResponse DeleteDeviceSolution(String deviceId){
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.withDeviceId(deviceId);
            try {
                DeleteDeviceResponse response = getIoTDAClient().deleteDevice(request);
                return response;
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
            return null;
        }

        // 查询设备影子
        public ShowDeviceShadowResponse queryServiceProperties(String iotId,String productId) {

            ICredential auth = new BasicCredentials()
                    .withProjectId(productId)
                    // 标准版/企业版需要使用衍生算法，基础版请删除配置"withDerivedPredicate";
                    .withDerivedPredicate(AbstractCredentials.DEFAULT_DERIVED_PREDICATE) // Used in derivative ak/sk authentication scenarios
                    .withAk(huaWeiIotConfigProperties.getAk())
                    .withSk(huaWeiIotConfigProperties.getSk());

            IoTDAClient client = IoTDAClient.newBuilder()
                    .withCredential(auth)
                    // 标准版/企业版：需自行创建Region对象，基础版：请使用IoTDARegion的region对象，如"withRegion(IoTDARegion.CN_NORTH_4)"
                    .withRegion(new Region(huaWeiIotConfigProperties.getRegionId(), huaWeiIotConfigProperties.getEndpoint()))
                    .build();
            ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
            request.withDeviceId(iotId);
            try {
                ShowDeviceShadowResponse response = client.showDeviceShadow(request);
                return response;
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
            return null;
        }


        // 查询产品信息
    public ShowProductResponse queryProductInfo(String productId) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productId);
        try {
            ShowProductResponse response = getIoTDAClient().showProduct(request);
            return response;
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
        return null;
    }
}
